
#if defined(ARDUINO)
 #if (ARDUINO < 100)
  #include "WProgram.h"
 #endif
#endif

#include "AMbera.h"


int sendMsg(int pinTx, char *msg)
{
  int base = BERA_BASE_LOW_LEN;
  int msgBuf[BERA_L1_MAX_DATA_BUFF];
  int i, j, k;

  for(j = 0; j < BERA_L1_MAX_PAYLOAD_SIZE; j++)
  {
    for(i = 0; i < 8; i++)
    {
      msgBuf[i+j*8] = bitRead(msg[j],i);
    }  
  }
  for (k = 1; k <= BERA_L1_MSG_RETRANS; k++)
  {
    // Send message
    for(i = 1; i <= BERA_L1_SYNC_PULSES; i++)
      {digitalWrite(pinTx, HIGH); delayMicroseconds(base);digitalWrite(pinTx, LOW);delayMicroseconds(base); } 

    for(i = 1; i <= BERA_L1_START_PULSES; i++) {
    digitalWrite(pinTx, HIGH); delayMicroseconds(BERA_L1_START_PULSE_LEN);digitalWrite(pinTx, LOW);delayMicroseconds(base);
    }

    for(i = 0; i < BERA_L1_MAX_PAYLOAD_SIZE * 8; i++)
    {
      if(msgBuf[i] == 0)
      {
        digitalWrite(pinTx, HIGH); delayMicroseconds(BERA_L1_DATA_SHORT_LEN);digitalWrite(pinTx, LOW);delayMicroseconds(base);
        digitalWrite(pinTx, HIGH); delayMicroseconds(BERA_L1_DATA_LONG_LEN);digitalWrite(pinTx, LOW);delayMicroseconds(base);
      }
      if(msgBuf[i]==1)
      {
        digitalWrite(pinTx, HIGH); delayMicroseconds(BERA_L1_DATA_LONG_LEN);digitalWrite(pinTx, LOW);delayMicroseconds(base);
        digitalWrite(pinTx, HIGH); delayMicroseconds(BERA_L1_DATA_SHORT_LEN);digitalWrite(pinTx, LOW);delayMicroseconds(base);
      }
    
    }
    delay(100);
  }
return(0);
}

  char* receiveMsg(int pinRx){

  char msgRx[BERA_L1_MAX_PAYLOAD_SIZE];
  int inBuf[BERA_L1_MAX_DATA_BUFF];
  int p[BERA_L1_START_PULSES];
  int found = 0;
  int res = 0;
  int i,j;
  int temp1,temp2;
   
  strcpy(msgRx,"void");

  found = 0;
  for(i = 0; i < BERA_L1_START_PULSES; i++) p[i] = 0;

  while(found < BERA_L1_START_PULSES)
  {
    for(i = BERA_L1_START_PULSES - 1 ; i > 0; i--) p[i] = p[i-1];
    p[0] = pulseIn(pinRx, HIGH);
    for(i = 0; i < BERA_L1_START_PULSES; i++)
    {
      if(p[i] > 1800 && p[i] < 2200) 
      {
        found++;
      }
      else
        found = 0;
    }
    //Serial.print(found);
  }
//====================================================
  if(found == BERA_L1_START_PULSES)
  {
   found = 0;
   int npulses = 0;
   while(npulses < BERA_L1_MAX_PAYLOAD_SIZE * 16)
   {
       int x = pulseIn(pinRx, HIGH);
       if(x > 300)
       {
           inBuf[npulses] = x;
           npulses++;
       }

   }

   for(j = 0; j < BERA_L1_MAX_PAYLOAD_SIZE; j++)
   {
     res = 0;
     for(i = j*8; i < (j+1)*8; i++)
     {
        temp1 = inBuf[2*i];
        temp2 = inBuf[2*i+1];
        if(temp1 > temp2)
        {
         bitSet(res,i-j*8);
        }
     }
     msgRx[j] = (char)res;
   }
   msgRx[BERA_L1_MAX_PAYLOAD_SIZE] = '\0';
   delay(100);
 }
 return msgRx;
}

